<?php

namespace app\api\model;

use think\Cache;
use app\common\library\wechat\WxUser;
use app\common\exception\BaseException;
use app\common\model\User as UserModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\dealer\Setting as DealerSettingModel;

/**
 * 用户模型类
 * Class User
 * @package app\api\model
 */
class User extends UserModel
{
    private $token;
	private $true_mobile = "";
	private $nickName = "";
	private $avatarUrl = "";
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'open_id',
        'is_delete',
        'wxapp_id',
        'create_time',
        'update_time'
    ];

    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getUser($token)
    {
        // mmmodify 此判断非常重要，直接影响到7天后token过期了，取用openid下标出错
        if(isset(Cache::get($token)['openid'])){
            $openId = Cache::get($token)['openid'];
            return self::detail(['open_id' => $openId], ['address', 'addressDefault', 'grade']);
        }
        else{
            return false;
        }
    }

    /**
     * 用户登录，小程序登录老版本，已作废
     */
    public function login($post)
    {
        // 微信登录 获取session_key
        $session = $this->wxlogin($post['code']);
        // 自动注册用户
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
		$userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
        $user_id = $this->register($session['openid'], $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid']);
        // 记录缓存, 7天
        Cache::set($this->token, $session, 86400 * 7);
        return $user_id;
    }
	/** 小程序注册登录步骤 1：首次进入小程序静默登录，根据code换算openid并入库 */
	public function login22($post)
	{
	    // 微信登录 获取session_key
	    $session = $this->wxlogin($post['code']);
	    // 自动注册用户
	    $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
		
	    // $userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
		if(isset($post['user_info']) && $post['user_info']!=''){
			$userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
		}
		else{
			$userInfo = array('nickName'=>'微信用户');
		}
		
	    $user_id = $this->register($session['openid'], $userInfo, $refereeId);
	    // 生成token (session3rd)
	    $this->token = $this->token($session['openid']);
	    // 记录缓存, 7天
	    Cache::set($this->token, $session, 86400 * 7);
		
		$back['user_id'] = $user_id;
		$back['nickName'] = $userInfo['nickName'];	// mmmodify
		$back['true_mobile'] = $this->true_mobile;
		$back['avatarUrl'] = $this->avatarUrl;
		$back['user_openid'] = $session['openid'];
	    return $back;
	}
	/**小程序获取头像之后，第二次通过openid计算token然后入库，每次进入小程序的时候，已做静默登录并缓存token ，此次主要设置本类的 $this->token */
	public function login33($post){
		// 微信登录 获取session_key
		$session = $this->wxlogin($post['code']);
		
		// 生成token (session3rd)
		$this->token = $this->token($session['openid']);
		// 记录缓存, 7天
		Cache::set($this->token, $session, 86400 * 7);
		$back['user_openid'] = $session['openid'];
		
		// 清空所有缓存	进入runtime，删除cache，删除temp
		// Cache::clear();
		return $back;
	}
	/**注册单页面微信公众号用户*/
	public function login44($post){
		// 自动获取推荐人数据
		$refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
		$wxappid = isset($post['wxappid']) ? $post['wxappid'] : 0;
		
		$user_id = $this->register($post['open_id'], $post, $refereeId, $wxappid);
		
		$back['user_id'] = $user_id;
		$back['nickName'] = $post['nickName'];	// mmmodify
		$back['true_mobile'] = $this->true_mobile;
		$back['avatarUrl'] = $this->avatarUrl;
		$back['user_openid'] = $post['open_id'];
		return $back;
	}
	public function getUserInfo($open_id){
		$userInfo = self::detail(['open_id' => $open_id]);
		return $userInfo;
	}
    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 根据code缓存并返回session，其中包含token
     */
    private function wxlogin($code)
    {
        // 获取当前小程序信息
        $wxConfig = Wxapp::getWxappCache();
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throw new BaseException(['msg' => '请到 [后台-小程序设置] 填写appid 和 appsecret']);
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        if (!$session = $WxUser->sessionKey($code)) {
            throw new BaseException(['msg' => $WxUser->getError()]);
        }
        return $session;
    }
	// 获取微信的手机号码 mmmodify
	public function getwxMobile($post){
		//获取手机号码，并将手机号码入库
		$userid = $post['user_id'];
		$encryptedData = $post['encryptedData'];
		$iv = $post['iv'];
		$code = $post['code'];

		$wxConfig = Wxapp::getWxappCache();
		$WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
		$true_mobile = $WxUser->getPhoneNum($encryptedData, $iv, $code);
		
		$back['true_mobile'] = $true_mobile ? $true_mobile : "";
		return $back;
	}
    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid)
    {
        $wxapp_id = self::$wxapp_id;
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$salt}");
    }

    /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    private function register($open_id, $data, $refereeId = null, $wxappid=0)
    {
        // 查询用户是否已存在
        $user = self::detail(['open_id' => $open_id]);
        $model = $user ?: $this;
        $this->startTrans();
        try {
            // mmmodify，如果用户不存在，才执行注册openid操作
			if(!$user){
				// 保存/更新用户记录
				if (!$model->allowField(true)->save(array_merge($data, [
					'open_id' => $open_id,
					'wxapp_id' => $wxappid>0 ? $wxappid : self::$wxapp_id
				]))) {
					throw new BaseException(['msg' => '用户注册失败']);
				}
			}
            // 记录推荐人关系 mmmodify, 此处!user在起初注册用户时确实为空
            // if (!$user && $refereeId > 0) {
			if ($refereeId > 0) {
                RefereeModel::createRelation($model['user_id'], $refereeId);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
		
		$this->true_mobile = isset($model['true_mobile']) ? $model['true_mobile'] : "";
		$this->nickName = isset($model['nickName']) ? $model['nickName'] : "";
		$this->avatarUrl = isset($model['avatarUrl']) ? $model['avatarUrl'] : "";
        return $model['user_id'];
    }

    /**
     * 个人中心菜单列表
     * @return array
     */
    public function getMenus()
    {
        $menus = [
            'address' => [
                'kk' => 1,
                'name' => '收货地址',
                'url' => 'pages/address/index',
                'icon' => 'map'
            ],
//            'coupon' => [
//                'kk' => 2,
//                'name' => '领券中心',
//                'url' => 'pages/coupon/coupon',
//                'icon' => 'lingquan'
//            ],
//            'my_coupon' => [
//                'kk' => 3,
//                'name' => '已领的券',
//                'url' => 'pages/user/coupon/coupon',
//                'icon' => 'youhuiquan'
//            ],
			
            // 'sharing_order' => [
            //     'kk' => 4,
            //     'name' => '拼团订单',
            //     'url' => 'pages/sharing/order/index',
            //     'icon' => 'pintuan'
            // ],
            // 'my_bargain' => [
            //     'kk' => 5,
            //     'name' => '我的砍价',
            //     'url' => 'pages/bargain/index/index?tab=1',
            //     'icon' => 'kanjia'
            // ],
			
//             'jfshop' => [
//                 'kk' => 4,
//                'name' => '积分商城',
//                'url' => 'pages/category/jflist?category_id=10002',
//                'icon' => 'shangcheng'
//            ],
			'dealer' => [
                'kk' => 5,
			    'name' => '推荐中心',
			    'url' => 'pages/dealer/index/index',
			    'icon' => 'fenxiaozhongxin'
			],
            // 'help' => [
            //     'kk' => 8,
            //     'name' => '帮助中心',
            //     'url' => 'pages/user/help/index',
            //     'icon' => 'help'
            // ],
        ];
        // 判断分销功能是否开启
        if (DealerSettingModel::isOpen()) {
            $menus['dealer']['name'] = DealerSettingModel::getDealerTitle();
        } else {
            unset($menus['dealer']);
        }
        return $menus;
    }

}
